<template>
  <div>
    <div class="create-commere-order">
      <ReturnInfo ref="returnInfo" v-model="paramsObj" :disabled="[2, 3].includes(paramsObj.dealStatus)" />
      <ReturnGoodsInfo v-model="paramsObj"/>
      <LogisticsInfo v-model="paramsObj.logisticsInfo" :show-other-fees="true" />
      <fixed-pagination>
        <div class="center">
          <el-button :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="toSubmit">保存</el-button>
          <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
        </div>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
import ReturnInfo from './module/returnInfo';
import ReturnGoodsInfo from './module/returnGoodsInfo';
import LogisticsInfo from './module/logisticsInfo';
import { mapState } from 'vuex';
import { editAfterSale, getAfterSaleDetail, addAfterSale } from '@/api/mengli';

export default {
  components: { LogisticsInfo, ReturnInfo, ReturnGoodsInfo },
  data() {
    return {
      isEdit: false,
      btnLoading: false,
      taxAmountDisabled: false,
      orderId: '',
      orderType: '',
      warehouseDefaultParams: [],
      paramsObj: {
        warehouse: '',
        payAmount: '',
        refundsStatus: '',
        orderNum: '',
        backAmount: '',
        returnsStatus: '',
        goodsCoding: '',
        number: '',
        goodsStatus: '',
        title: '',
        partialOrFullrefund: '',
        reason: '',
        cost: '',
        logisticsInfo: {
          warehouseFees: '',
          otherFees: '',
          invoiceTime: '',
          address: '',
          invoiceNum: '',
          cost: ''
        }
      },
      orderStatus: null,
      moneyKey: ['payAmount', 'backAmount', 'otherFees', 'warehouseFees', 'cost']
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    })
  },
  created() {
    this.orderId = Number(this.$route.params.id) || '';
    this.orderType = this.$route.query.type || '2';
    if (this.orderId) {
      this.isEdit = true;
      this.getDetail();
    } else {
      this.isEdit = false;
    }
  },
  methods: {
    getDetail() {
      getAfterSaleDetail(this.orderId).then(res => {
        if (res.data) {
          // writeOffStatus 核销状态（0: '待核销', 1: '已完成', 2: '部分核销'）
          // 已完成和部分核销后不能编辑价格
          /* this.taxAmountDisabled = res.data.writeOffStatus === 1 || res.data.writeOffStatus === 2;
          res.data.payTime = res.data.payTime ? res.data.payTime * 1000 : null;
          if (res.data.orderCreateTime && res.data.orderCreateTime.toString().length === 10) {
            res.data.orderCreateTime = res.data.orderCreateTime * 1000;
          }
          res.data.price = Number(res.data.price) / 100;
          res.data.warehouseId = res.data.warehouseId ? res.data.warehouseId : 1;
          if (res.data.warehouseId && res.data.warehouse) {
            this.warehouseDefaultParams = [{ repositoryId: res.data.warehouseId, repositoryName: res.data.warehouse }];
          }
          this.orderStatus = this.paramsObj.orderStatus; */
          res.data.partialOrFullrefund = Number(res.data.partialOrFullrefund);
          this.paramsObj = res.data;
          this.paramsObj.logisticsInfo = this.paramsObj.logisticsInfo || {};
          (this.paramsObj.goodsCoding && this.paramsObj.warehouseId) && (this.paramsObj.goodsCoding = this.paramsObj.goodsCoding + '+' + this.paramsObj.warehouseId);
          this.moneyKey.forEach(item => {
            if (this.paramsObj[item]) this.paramsObj[item] = Number(this.paramsObj[item]) / 100;
            if (this.paramsObj.logisticsInfo[item]) this.paramsObj.logisticsInfo[item] = Number(this.paramsObj.logisticsInfo[item]) / 100;
          });
          this.$refs['returnInfo'] && this.$refs['returnInfo'].searchOrderNum(res.data.orderNum);
        }
      });
    },
    /**
     * 操作
     */
    toSubmit() {
      const params = JSON.parse(JSON.stringify(this.paramsObj));
      const promise = [];
      promise.push(this.$refs['returnInfo'].validate());
      Promise.all(promise).then(() => {
        this.moneyKey.forEach(item => {
          if (params[item]) params[item] = Math.round(Number(params[item]) * 100);
          if (params.logisticsInfo[item]) params.logisticsInfo[item] = Math.round(Number(params.logisticsInfo[item]) * 100);
        });
        params.goodsCoding && (params.goodsCoding = params.goodsCoding.split('+')[0]);
        if (this.isEdit) {
          this.edit(params);
        } else {
          this.add(params);
        }
      }).catch((e) => {
        console.log(e);
      });
    },
    edit(params) {
      editAfterSale(this.orderId, params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.$router.push({
            name: 'mengliOrderDetail',
            params: { id: this.orderId },
            query: { type: 3 }
          });
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    add(params) {
      this.btnLoading = true;
      addAfterSale(params).then(res => {
        this.btnLoading = false;
        if (res.code === 200) {
          this.$message.success('保存成功');
          this.toBack();
        } else {
          this.$message.error(res.message);
        }
      }).catch(() => {
        this.btnLoading = false;
      });
    },
    toBack() {
      const source = this.$route.query.source;
      const query = {};
      if (!source || source !== 'all') {
        query.type = 3;
      }
      this.$router.push({
        name: 'mengliOrder',
        query
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.create-commere-order {
  min-height: calc(100vh - 120px);
  background:rgba(255,255,255,1);
  padding: 24px;
}
.one-cell {
  width: 100%;
}
.tip {
  position: absolute;
  left: 0;
}

</style>
<style lang="scss">
  .global-select-down.ip-image .el-select-dropdown__item span {
    display: inline-block;
    width: calc(100% - 14px);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
</style>
